package net.sppan.base.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

import net.sppan.base.config.httpConfig.HttpAPIService;
import net.sppan.base.config.redis.RedisTemplateUtil;
import net.sppan.base.dao.IContentExuserDao;
import net.sppan.base.dao.support.IBaseDao;
import net.sppan.base.entity.ContentExuser;
import net.sppan.base.entity.DyContexts;
import net.sppan.base.entity.ExContentView;
import net.sppan.base.service.IContentExuserService;
import net.sppan.base.service.specification.SimpleSpecificationBuilder;
import net.sppan.base.service.specification.SpecificationOperator.Operator;
import net.sppan.base.service.support.impl.BaseServiceImpl;
@Service
public class ContentExuserServiceImpl extends BaseServiceImpl<ContentExuser, Long> implements IContentExuserService {

	@Value("${DY.EX.HTTPURL}")
	private String httpUrl;
	
	@Value("${DY.EX.TOKEN}")
	private String token;
	
	@Autowired
    private IContentExuserDao contentExuserDao;
	
	@Autowired
	private HttpAPIService apiService;
	@Autowired
	private RedisTemplateUtil redisTemplateUtil;
	
	@Override
	public IBaseDao<ContentExuser, Long> getBaseDao() {
		return this.contentExuserDao;
	}
	@Override
	public void saveList(List<ContentExuser> contentExusers) {
		contentExuserDao.saveAll(contentExusers);
	}
 
	/**
	 * 审核任务分配（审核人员）
	 * @param userId
	 * @param roleId
	 */
	@Async("distributionAsync")
	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED)
	public synchronized void distributionBy (String userId,String dyId,Integer size){
		SimpleSpecificationBuilder<ContentExuser> builder = new SimpleSpecificationBuilder<ContentExuser>();
		if(userId!=null){
			builder.add("exuserId", Operator.eq.name(), userId);
			builder.add("exResult", Operator.eq.name(), "0");
			List<ContentExuser> contentExusers=contentExuserDao.findAll(builder.generateSpecification());
			if(contentExusers!=null&&contentExusers.size()<20){//当前用户下未审核小于20 开始分配新审核段子
				SimpleSpecificationBuilder<ContentExuser> builder2 = new SimpleSpecificationBuilder<ContentExuser>();
				builder2.add("exResult", Operator.eq.name(), "0");
				builder2.add("exuserId", Operator.isNull.name(), "123");
				Page<ContentExuser> pageContentExusers=contentExuserDao.findAll(builder2.generateSpecification(),new PageRequest(0, 100-contentExusers.size(), new Sort(Direction.DESC, "uploadDate")));
				for(ContentExuser contentExuser:pageContentExusers.getContent()){
					contentExuserDao.updateContentExuserDao("0", Long.valueOf(userId), new Date(),contentExuser.getId());
				}
		     }
		}else if(dyId !=null){
			builder.add("exuserId", Operator.eq.name(), "0");
			builder.add("exResult", Operator.eq.name(), "0");
			builder.add("exdyId", Operator.eq.name(), dyId);
			if(size!=null&&size <20){
				SimpleSpecificationBuilder<ContentExuser> builder2 = new SimpleSpecificationBuilder<ContentExuser>();
				builder2.add("exResult", Operator.eq.name(), "0");
				builder2.add("exuserId", Operator.isNull.name(), "123");
				Page<ContentExuser> pageContentExusers=contentExuserDao.findAll(builder2.generateSpecification(),new PageRequest(0, 100-size, new Sort(Direction.DESC, "uploadDate")));
				for(ContentExuser contentExuser:pageContentExusers.getContent()){
					contentExuserDao.updateContentDyIdDao("0", dyId, new Date(),contentExuser.getId());
				}
			}
		}
	} 
	
	/**
	 * app 用户审核
	 */
	@Override
	public Long upateExConten(ContentExuser exuserContent) {
		Long countNum= 0L;
		if(exuserContent!=null&&exuserContent.getId()!=null){
			ContentExuser dbContentExuser= find(exuserContent.getId());
			if(dbContentExuser.getExResult().equals("0")){
				dbContentExuser.setExResult(exuserContent.getExResult());
				dbContentExuser.setOperationCode(exuserContent.getOperationCode());
				dbContentExuser.setExTime(new Date()); 
				dbContentExuser.setExDesc(null);
				dbContentExuser.setExuserId(exuserContent.getExuserId());
				if(exuserContent.getExResult().equals("1")||exuserContent.getExResult().equals("2")){
					try {
						postExResultHttp(dbContentExuser.getDyContentId(), exuserContent.getExResult());
						dbContentExuser.setSysStatus("2");//设置同步状态
						update(dbContentExuser);
						countNum=setExtaskNum(exuserContent.getExuserId()); 
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return countNum;
	}
	
	public Long setExtaskNum(Long exuserId){
		Long num = 0L;
		String value = (String) redisTemplateUtil.get("exuser:taks:num:"+exuserId);
		if(value !=null && !value.equals("")){
			num = Long.valueOf(value)+1;
		}else{
			num= num+1;
		}
		redisTemplateUtil.set("exuser:taks:num:"+exuserId,String.valueOf(num),36000);
		return num;
	}
	
	@Override
	public Long getExtaskNum(Long exuserId){
		Long num = 0L;
		String value = (String) redisTemplateUtil.get("exuser:taks:num:"+exuserId);
		if(value !=null && !value.equals("")){
			num = Long.valueOf(value);
		}
		return num; 
	}
	
	
	@Override
	public Map<String, Object> updateExDyIdContent(ContentExuser exuserContent){
		Map<String, Object> map = new HashMap<String, Object>();
		ContentExuser contentExuser=contentExuserDao.findByDyId(exuserContent.getExdyId(), exuserContent.getDyContentId());
		if(contentExuser!=null){
			contentExuser.setOperationCode(exuserContent.getOperationCode());
			contentExuser.setExResult(exuserContent.getExResult());
			contentExuser.setExTime(new Date());
			try {
				postExResultHttp(contentExuser.getDyContentId(), contentExuser.getExResult());
				contentExuser.setSysStatus("2");//设置同步状态
				update(contentExuser);
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put("respMessage", "ok");
			map.put("respCode", "0");
			map.put("isUsed", true);
		}else{
			map.put("respMessage", "当前审核以无效，请刷新！");
			map.put("respCode", "");
			map.put("isUsed", false);
		}  
		return map;
	}
	
	
	@Async("distributionAsync")
	public  void  postExResultHttp(Long dyContentId ,String exResult) throws Exception{
		//1qaz@WSX1234QWER
		Map<String, Object> params =new HashMap<String, Object>();
		params.put("dyID", 3991234);
		params.put("type", 4);
		params.put("operator", Integer.parseInt(exResult));
		List<Integer> dyDataID =new ArrayList<Integer>();
		dyDataID.add(dyContentId.intValue());
		params.put("dyDataID", dyDataID);
		params.put("token", token);
		params.put("deviceID",String.valueOf(System.currentTimeMillis()));
		String vss = null;
	    vss = apiService.doPost(httpUrl, JSON.toJSONString(params)); 
		System.out.println(vss);
	}
	
	
	@Override
	public Page<DyContexts> findContentExuserByDyId(String dyId,Long countentId, Pageable pageable) {
		return contentExuserDao.findContentExuserByDyId(dyId,countentId, pageable);
	}
	@Override
	public Page<ExContentView> findContentExuserByUserId(Long userId ,Pageable pageable){
		return contentExuserDao.findContentExuserByUserId(userId, pageable);
	}
//	/**
//	 * APP 用户分配审核 段子
//	 * @param userId
//	 * @param roleId
//	 */
//	public void distributionByDyUser(String dyUserId ){
//		SimpleSpecificationBuilder<ContentExuser> builder = new SimpleSpecificationBuilder<ContentExuser>();
//		builder.add("dyId", Operator.eq.name(), dyUserId);
//		builder.add("userId", Operator.eq.name(),userId);
//		contentExuserDao.getOne(id);
//	}
	@Override
	public void updateContentExuserBlocked(String publisherDyId) {
		SimpleSpecificationBuilder<ContentExuser> builder = new SimpleSpecificationBuilder<ContentExuser>();
		builder.add("publisherDyId", Operator.eq.name(), publisherDyId);
		builder.add("exResult", Operator.eq.name(),"0");
		List<ContentExuser> contentExusers = findList(builder.generateSpecification(),new Sort(Direction.DESC,"allotTime"));
		for(ContentExuser contentExuser:contentExusers){
			contentExuser.setExResult("3"); 
			contentExuser.setExTime(new Date()); 
			contentExuser.setExDesc("禁言操作");
			contentExuser.setExuserId(null);
			contentExuser.setOperationCode(null);
			try {
				postExResultHttp(contentExuser.getDyContentId() ,"2");
				update(contentExuser);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
}
